#include "xcamera_config.h"

#include <cstring>
#include <fstream>

void XCameraConfig::Push(const XCameraData &data) {
  std::unique_lock<std::mutex> lk(mux_);
  cames_.push_back(data);
}
int XCameraConfig::GetCamCount() {
  std::unique_lock<std::mutex> lk(mux_);
  return cames_.size();
}
XCameraData XCameraConfig::GetCam(int index) {
  std::unique_lock<std::mutex> lk(mux_);
  if (index < 0 || index >= cames_.size()) {
    return XCameraData();
  }
  return cames_[index];
}

bool XCameraConfig::DelCam(int index) {
  std::unique_lock<std::mutex> lk(mux_);
  if (index < 0 || index >= cames_.size()) {
    return false;
  }
  cames_.erase(cames_.begin() + index);
  return true;
}

bool XCameraConfig::SetCam(int index, const XCameraData &data) {
  std::unique_lock<std::mutex> lk(mux_);
  if (index < 0 || index >= cames_.size()) {
    return false;
  }
  cames_[index] = data;
  return true;
}

bool XCameraConfig::Load(const char *path) {
  if (!path)
    return false;
  std::ifstream ifs(path, std::ios::binary);
  if (!ifs)
    return false;
  XCameraData data;
  cames_.clear();
  std::unique_lock<std::mutex> lk(mux_);
  while (!ifs.eof()) {
    ifs.read((char *)&data, sizeof(data));
    if (ifs.gcount() != sizeof(data)) {
      ifs.close();
      return true;
    }
    cames_.push_back(data);
  }
  ifs.close();
  return true;
}

bool XCameraConfig::Save(const char *path) {
  if (!path)
    return false;
  std::ofstream ofs;
  ofs.open(path, std::ios::binary);
  if (!ofs) {
    return false;
  }
  std::unique_lock<std::mutex> lk(mux_);
  for (auto cam : cames_) {
    ofs.write((char *)&cam, sizeof(cam));
    ofs << std::flush;
  }
  ofs.close();
  return true;
}



bool XCameraConfig::Replace(int index, const XCameraData &data) {
  std::unique_lock<std::mutex> lk(mux_);
  if (index < 0 || index >= cames_.size()) {
    return false;
  }
  strcpy(cames_[index].name, data.name);
  strcpy(cames_[index].url, data.url);
  strcpy(cames_[index].sub_url, data.sub_url);
  strcpy(cames_[index].save_path, data.save_path);
  return true;
}

XCameraConfig::XCameraConfig() {}
